<?php
	if(!defined('__APPLICATION__')){
		require_once dirname(__FILE__) . '/core/autoload.php';
	
		$vapp = !empty($_GET['mrwapp']);
		$vdir = !empty($_GET['mrwdir']);
		
		$app = $vapp ? $_GET['mrwapp'] : null;
		$dir = $vdir ? $_GET['mrwdir'] : null;
		
		if($vapp){
			unset($_GET['mrwapp'], $_REQUEST['mrwapp']);
		}
		
		if($vdir){
			unset($_GET['mrwdir'], $_REQUEST['mrwdir']);
		}
		
		function appURL($application, $directive = '', $get = '', $anchor = ''){
			if(defined('NIMP_MOD_REWRITE') && NIMP_MOD_REWRITE){
				if(is_array($get)){
					$gets = array();
					foreach($get as $k => $v) $gets[] = $k . '=' . $v;
					$get = implode('&', $gets);
				}
				
				$link = URL_BASE . '/apps/' . $application . '/';
				
				if(!empty($directive)){
					$link .= $directive . '/';
				}
				
				if(!empty($get)){
					$link .= '?' . $get;
				}
				
				if(!empty($anchor)){
					$link .= '#' . $anchor;
				}
				
				return $link;
			}else{
				if(is_array($get)){
					$gets = array();
					foreach($get as $k => $v) $gets[] = $k . '=' . $v;
					$get = implode('&', $gets);
				}else{
					$get .= '&mrwapp=' . $application . (!empty($directive) ? '&mrwdir=' . $directive : '');
				}
				
				$link = URL_BASE . '/';
				
				if(!empty($get)){
					$link .= '?' . $get;
				}
				
				if(!empty($anchor)){
					$link .= '#' . $anchor;
				}
				
				return $link;
			}
		}
		
		if(!session_start()){
			throw new ApplicationException('Session could not be started.');
		}
		
		if($vapp){
			$am = new ApplicationManifest(new File(PATH_CORE_CONFIGS . DS . 'applications.ini'));
			
			if($am->hasApplication($app)){
				$d = $am->getApplication($app);
				$application = $d->load();
				
				define('__APPLICATION__', $app);
				define('NIMP_MOD_REWRITE', $am->get('useModRewrite', false));
				
				if($application instanceof ApplicationDirectiveAcceptor){
					$application->acceptDirective($app, $dir, $_GET, $_POST, $_SESSION);
				}
				
				$dob = $application->doOutput();
				unset($application);
				
				echo $dob;
			}else{
				throw new Exception('Application ' . $app . ' does not exist!');
			}
		}else{
			$am = new ApplicationManifest(new File(PATH_CORE_CONFIGS . DS . 'applications.ini'));
			
			if($am->hasDefault()){
				$d = $am->getDefault();
				$app = $d->getName();
				$application = $d->load();
				
				define('__APPLICATION__', $app);
				define('NIMP_MOD_REWRITE', $am->get('useModRewrite', false));
				
				if($application instanceof ApplicationDirectiveAcceptor){
					$application->acceptDirective($app, $dir, $_GET, $_POST, $_SESSION);
				}
				$dob = $application->doOutput();
				unset($application);
				
				echo $dob;
			}else{
				throw new Exception('No default application specified!');
			}
		}
	}
?>